package com.cloud.base.proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author liuyuan
 * @Date 2020-01-16 11:23
 * @Version 1.0
 */
@Component
public class ApiRegistryBean implements ApplicationContextAware, BeanDefinitionRegistryPostProcessor, ResourceLoaderAware {

    private ApplicationContext ctx;


    /**
     * Spring容器注入
     */
    private ResourceLoader resourceLoader;

    private ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
    private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
    private static final String FULLTEXT_SACN_PACKAGE_PATH = "com.channel";

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        Set<Class<?>> classes = null;
        try {
            classes = doScan(FULLTEXT_SACN_PACKAGE_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Iterator<Class<?>> it = classes.iterator();
        while (it.hasNext()) {
            Class<?> next = it.next();
            // 需要被代理的接口
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(next);
            GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
            definition.getPropertyValues().add("interfaceClass", definition.getBeanClassName());
            definition.setBeanClass(ApiProxyFactory.class);
            definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
            // 注册bean名,一般为类名首字母小写
            String className = getClassName(next.getName());
            System.out.println("className:"+className);
            beanDefinitionRegistry.registerBeanDefinition(className, definition);
        }

    }



    private String getClassName(String classPath){
        String replace = classPath.replace(".", "/");
        String[] splits = replace.split("/");
        String name = splits[splits.length - 1];
        return toLowerCaseFirstOne(name);
    }


    //首字母转小写
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }





    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {


    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        if (this.resourceLoader == null) {
            this.resourceLoader = resourceLoader;
        }

    }

    /**
     * 利用spring提供的扫描包下面的类信息,再通过classfrom反射获得类信息
     *
     * @param scanPath
     * @return
     * @throws IOException
     */
    public Set<Class<?>> doScan(String scanPath) throws IOException {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                .concat(ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(scanPath))
                        .concat("/**/*.class"));
        Resource[] resources = resolver.getResources(packageSearchPath);
        MetadataReader metadataReader = null;
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                metadataReader = metadataReaderFactory.getMetadataReader(resource);
                try {
                    // 当类型是抽象类或接口在添加到集合
                    if (!metadataReader.getClassMetadata().isConcrete()) {
                        classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return classes;
    }

    /**
     * 指定包下面的类信息
     *
     * @return 多个类信息
     */
  /*  public static Set<Class<?>> classInfos() {
        try {
            String scanPath = MallApplication.getApplicationContext().getEnvironment()
                    .getProperty(FULLTEXT_SACN_PACKAGE_PATH);
            return new ScanSupport().doScan(scanPath);
        } catch (Exception e) {
            Assert.RuntimeException("扫描包类信息错误");
        }
        return null;
    }*/

}
